package cn.kailangtu.myapplication.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.Nullable;

public class AutoMeterView extends View {
    private DisplayMetrics displayMetrics;
    private TextPaint mPaint;
    private TextPaint mPaint1;
    //刻度的大小
    private float lineWidth = 5;
    //直针和中间圆的大小
    private float outlineWidth = 4;
//    半圆弧
    private float outlineWidth1 = 15;
//直针最大系数 1最大数据100  2最大速度100
    private float xishu1 = 1;

    //    半圆弧
    //速度文字大小
    private float textSize = 20;
    private float sumDegree = 360f;
    Rect bounds = new Rect();
    RectF rectF = new RectF();
    float degreeOffset = 0;

    private ValueAnimator mDegreeAnimator;

    public AutoMeterView(Context context) {
        this(context, null);
    }

    public AutoMeterView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoMeterView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        displayMetrics = context.getResources().getDisplayMetrics();
        initPaint();
    }

    private void initPaint() {
        // 实例化画笔并打开抗锯齿
        mPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(dpTopx(textSize));

        mPaint1 = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        mPaint1.setAntiAlias(true);
        mPaint1.setStrokeCap(Paint.Cap.ROUND);

    }

    private float dpTopx(float dp) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    public void setSumDegree(float sumDegree) {
        this.sumDegree = sumDegree;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        if (widthMode != MeasureSpec.EXACTLY) {
            widthSize = displayMetrics.widthPixels / 2;
        }

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        if (heightMode != MeasureSpec.EXACTLY) {
            heightSize = displayMetrics.widthPixels / 2;
        }

        //来个正方形大小
        widthSize = heightSize = Math.min(widthSize, heightSize);

        setMeasuredDimension(widthSize, heightSize);
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth();
        int height = getHeight();

        mPaint.setStyle(Paint.Style.STROKE);

        mPaint.setStrokeWidth(dpTopx(outlineWidth1));


        mPaint1.setStyle(Paint.Style.STROKE);

        mPaint1.setStrokeWidth(dpTopx(outlineWidth1));


        float strokeWidth = mPaint.getStrokeWidth();

        float outRadius = (float) (Math.min(width / 2, height / 2));
        float innerRadius =  (outRadius - 3 * strokeWidth);
        float innerDotRadius =  (outRadius - 2 * strokeWidth);

        float perDegree = sumDegree / 100;

        int saveCount = canvas.save();
        canvas.translate(width / 2F, height / 2F);
        canvas.rotate(-90);


        int[] colorSweep = new int[]{0xFF10dbff,0xFF10dbff,0xFF10dbff,0xFF10dbff};
        float[] position = new float[]{0f, 0.36f, 0.5f, 0.7f};
        SweepGradient mShader = new SweepGradient(getMeasuredWidth() / 2, getMeasuredHeight() / 2, colorSweep, position);



        mPaint.setColor(0xff54d68c);
        mPaint1.setShader(mShader);
        rectF.set(-width / 2F + strokeWidth / 2, -height / 2F + strokeWidth / 2, width / 2F - strokeWidth / 2, height / 2F - strokeWidth / 2);

        canvas.drawArc(rectF, 0, - (degreeOffset * xishu1 * perDegree), false, mPaint1);

        mPaint.setColor(0xffff9922);
        //canvas.drawArc(rectF, 20 * perDegree, 60 * perDegree, false, mPaint);

        mPaint.setColor(Color.RED);
       // canvas.drawArc(rectF, 80 * perDegree, 20 * perDegree, false, mPaint);

        mPaint.setStrokeWidth(dpTopx(lineWidth));
        strokeWidth = mPaint.getStrokeWidth();
        outRadius = (int) (Math.min(width / 2, height / 2));
        innerRadius = (int) (outRadius - 4 * strokeWidth);
        innerDotRadius = (int) (outRadius - 3 * strokeWidth);

//        for (int i = 0; i <=100; i++) {
//            float innerLineRadius = innerDotRadius;
//            if (i % 5 == 0) {
//                mPaint.setStrokeWidth(strokeWidth / 2);
//                innerLineRadius = innerRadius;
//            } else {
//                mPaint.setStrokeWidth(strokeWidth / 4);
//            }
//
//            float startX = (float) (innerLineRadius * Math.cos(Math.toRadians(i * perDegree*xishu1)));
//            float startY = (float) (innerLineRadius * Math.sin(Math.toRadians(i * perDegree*xishu1)));
//
//            float endX = (float) (outRadius * Math.cos(Math.toRadians(i * perDegree*xishu1)));
//            float endY = (float) (outRadius * Math.sin(Math.toRadians(i * perDegree*xishu1)));
////刻度
//            mPaint.setColor(getPaintColor(i));
//            canvas.drawLine(startX, startY, endX, endY, mPaint);
//
//        }

        canvas.restoreToCount(saveCount);

//        saveCount = canvas.save();
//        mPaint.setStyle(Paint.Style.FILL);
//        canvas.translate(width / 2F, height / 2F);
//        canvas.rotate(-90 - 45);
//        //该方法旋转的是坐标系，而不是图层
//
//        for (int i = 0; i <= 10; i++) {
//            if (i > 0) {
//                canvas.rotate(perDegree * 10);
//                //每次旋转坐标系一定的位置
//            }
//            mPaint.setColor(getPaintColor(i * 5));
//            String text = String.valueOf(i * 5);
//            mPaint.getTextBounds(text, 0, text.length(), bounds);
//            float textBaseline = innerRadius - strokeWidth - bounds.height() + getTextPaintBaseline(mPaint);
//          // 数字
//            canvas.drawText(text, 0 - bounds.width() / 2F, -textBaseline, mPaint);
//            //从y轴负方向开始绘制
//
//        }
//        canvas.restoreToCount(saveCount);

        saveCount = canvas.save();
        canvas.translate(width / 2F, height / 2F);
        mPaint.setColor(getPaintColor(degreeOffset));
        int tail = (int) dpTopx(outlineWidth);



        canvas.restoreToCount(saveCount);

    }

    private int getPaintColor(float degreeOffset) {
        if (degreeOffset <= 10) {
            return 0xff54d68c;
        } else if (degreeOffset > 10 && degreeOffset <41) {
            return 0xffff9922;
        } else {
            return Color.RED;
        }
    }

    /**
     * 基线到中线的距离=(Descent+Ascent)/2-Descent
     * 注意，实际获取到的Ascent是负数。公式推导过程如下：
     * 中线到BOTTOM的距离是(Descent+Ascent)/2，这个距离又等于Descent+中线到基线的距离，即(Descent+Ascent)/2=基线到中线的距离+Descent。
     */
    public static float getTextPaintBaseline(Paint p) {
        Paint.FontMetrics fontMetrics = p.getFontMetrics();
        return (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent;
    }

   float currTargetDegreeOffset=0;
    float bounceOffset = 0;
    int xishu = 0;
    public void setDegreeOffset(float targetDegreeOffset) {
        currTargetDegreeOffset = targetDegreeOffset;
        if (targetDegreeOffset < 0) {
            targetDegreeOffset = 0;
        }
        if (targetDegreeOffset > 100) {
            targetDegreeOffset = 100;
        }

        if (this.degreeOffset == targetDegreeOffset) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            this.degreeOffset = targetDegreeOffset;
            return;
        }

        if (mDegreeAnimator != null) {
            mDegreeAnimator.cancel();
        }
        float perDegree = sumDegree / 100;


        if (this.degreeOffset > targetDegreeOffset) {
            bounceOffset = targetDegreeOffset - perDegree * xishu;
            if (bounceOffset < 0) {
                bounceOffset = 0;
            }
        } else {
            bounceOffset = targetDegreeOffset + perDegree * xishu;
            if (bounceOffset > 100) {
                bounceOffset = 100;
            }
        }
        mDegreeAnimator = ValueAnimator.ofFloat(this.degreeOffset, bounceOffset, targetDegreeOffset);
        mDegreeAnimator.setDuration(500);
        mDegreeAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                postUpdateDegree((Float) animation.getAnimatedValue());
            }
        });
        mDegreeAnimator.start();
    }
    private void postUpdateDegree(float animatedValue) {
        this.degreeOffset = animatedValue;
        postInvalidate();
    }
}
